package com.gitee.sparta.core.cluster.strategy;

import com.gitee.sparta.core.bean.cluster.ClusterCmd;
import com.gitee.sparta.common.helpers.IsolationHelper;
import com.gitee.sparta.core.bean.cluster.ClusterProtocol;
import com.gitee.sparta.core.bean.cluster.ServerBean;
import com.gitee.sparta.core.cluster.AbstractClusterLeader;
import com.gitee.sparta.core.cluster.ClusterCache;
import com.gitee.sparta.core.cluster.balance.LoadBalance;
import com.gitee.sparta.core.property.SpartaCoreProperties;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;

import java.nio.channels.SocketChannel;

/**
 * <p>
 * 发生了选举，选举之前是 follower 角色的，选举后依然是 follower 角色
 * 选举后 原本的 follower 注册到新的 leader 上指令处理策略
 * </p>
 *
 * @author zyred
 * @since v 0.0.2
 */
@Slf4j
public class NextFollowerStrategy extends Strategy {

    public NextFollowerStrategy(RedissonClient client,
                                LoadBalance loadBalance,
                                SpartaCoreProperties properties) {
        super(client, loadBalance, properties);
    }

    @Override
    public void handle(ChannelHandlerContext ctx, SocketChannel sc, ClusterProtocol cp) {
        RMap<Integer, ServerBean> serverTab = client.getMap(properties.getServerTable());

        // 注册 follower 到 leader 中
        ServerBean bean = serverTab.get(cp.getServerId());
        ClusterCache.putServerInfo(cp.getServerId(), bean);

        if (ClusterCache.isNetty()) {
            ClusterCache.putClient(ctx.channel(), cp.getServerId());
        } else {
            ClusterCache.putClient(sc, cp.getServerId());
        }

        log.info("[Sparta] Follower again follower, sid: {}", cp.getServerId());

        // 注册服务负载均衡
        String isolation = IsolationHelper.isolation(cp.getServerId());
        this.loadBalance.addNode(isolation, cp.getServerId());

        cp.setLeaderSid(ClusterCache.getServerId());
        cp.setCmd(ClusterCmd.CHANNEL_ACCEPT);
        cp.setChannel(ctx.channel());
        AbstractClusterLeader.sendQueue(cp);
    }

}
